package com.example.smartpark.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.smartpark.common.Result;
import com.example.smartpark.dto.ParkingRecordDTO;
import com.example.smartpark.dto.ParkingRecordQueryDTO;
import com.example.smartpark.service.ParkingRecordService;
import com.example.smartpark.service.VehicleService;
import com.example.smartpark.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 停车记录控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/parking-records")
public class ParkingRecordController {

    @Autowired
    private ParkingRecordService parkingRecordService;

    @Autowired
    private VehicleService vehicleService;

    /**
     * 分页查询停车记录
     *
     * @param queryDTO 查询条件
     * @return 停车记录分页结果
     */
    @GetMapping
    public Result<IPage<ParkingRecordDTO>> getParkingRecordPage(ParkingRecordQueryDTO queryDTO) {
        log.info("分页查询停车记录: queryDTO={}", queryDTO);
        
        // 如果是查询当前在场车辆
        if ("current".equals(queryDTO.getType())) {
            // 强制设置状态为"进行中"
            queryDTO.setStatus(0);
            // 强制设置未出场
            queryDTO.setExitTime(null);
        }
        
        return Result.success(parkingRecordService.getParkingRecordPage(queryDTO));
    }

    /**
     * 查询停车记录详情
     *
     * @param id 停车记录ID
     * @return 停车记录详情
     */
    @GetMapping("/{id}")
    public Result<ParkingRecordDTO> getParkingRecordById(@PathVariable Long id) {
        log.info("查询停车记录详情: id={}", id);
        return Result.success(parkingRecordService.getParkingRecordById(id));
    }

    /**
     * 创建停车记录（入场）
     *
     * @param parkingRecordDTO 停车记录DTO
     * @return 创建的停车记录
     */
    @PostMapping
    public Result<ParkingRecordDTO> createParkingRecord(@RequestBody @Valid ParkingRecordDTO parkingRecordDTO) {
        log.info("创建停车记录: parkingRecordDTO={}", parkingRecordDTO);
        return Result.success(parkingRecordService.createParkingRecord(parkingRecordDTO));
    }

    /**
     * 更新停车记录（出场）
     *
     * @param id 停车记录ID
     * @param parkingRecordDTO 停车记录DTO
     * @return 更新后的停车记录
     */
    @PutMapping("/{id}")
    public Result<ParkingRecordDTO> updateParkingRecord(
            @PathVariable Long id,
            @RequestBody ParkingRecordDTO parkingRecordDTO) {
        log.info("更新停车记录: id={}, parkingRecordDTO={}", id, parkingRecordDTO);
        return Result.success(parkingRecordService.updateParkingRecord(id, parkingRecordDTO));
    }

    /**
     * 计算停车费用
     *
     * @param id 停车记录ID
     * @return 计算费用后的停车记录
     */
    @GetMapping("/{id}/calculate-fee")
    public Result<ParkingRecordDTO> calculateParkingFee(@PathVariable Long id) {
        log.info("计算停车费用: id={}", id);
        return Result.success(parkingRecordService.calculateParkingFee(id));
    }

    /**
     * 更新支付状态
     *
     * @param id 停车记录ID
     * @param paymentId 支付ID
     * @return 更新后的停车记录
     */
    @PutMapping("/{id}/payment")
    public Result<ParkingRecordDTO> updatePaymentStatus(
            @PathVariable Long id,
            @RequestParam Integer paymentId) {
        log.info("更新支付状态: id={}, paymentId={}", id, paymentId);
        return Result.success(parkingRecordService.updatePaymentStatus(id, paymentId));
    }

    @GetMapping("/user")
    public Result<IPage<ParkingRecordDTO>> getUserParkingRecords(
            ParkingRecordQueryDTO queryDTO,
            @RequestHeader("Authorization") String token) {
        log.info("查询用户停车记录: queryDTO={}", queryDTO);
        
        // 从token中获取用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
        
        // 根据用户ID查询该用户的所有车辆ID
        List<Integer> vehicleIds = vehicleService.getUserVehicleIds(userId);
        
        // 设置查询条件
        if (!vehicleIds.isEmpty()) {
            queryDTO.setVehicleIds(vehicleIds);
        } else {
            // 如果用户没有车辆，返回空结果
            return Result.success(new Page<>(queryDTO.getPage(), queryDTO.getSize()));
        }
        
        return Result.success(parkingRecordService.getParkingRecordPage(queryDTO));
    }
} 